package com.duing.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duing.common.PageResult;
import com.duing.common.ResponseResult;
import com.duing.dto.UserDTO;
import com.duing.entity.User;
import com.duing.enums.ErrorCode;
import com.duing.service.impl.UserServiceImpl;
import com.duing.vo.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/add")
    public ResponseResult<User> addUser(@Valid User user){
        userService.validateUser(user);
        userService.save(user);
        return ResponseResult.success(user);
    }

    @PostMapping("/delete")
    public ResponseResult<Boolean> deleteUser(Long id){
        boolean result = userService.removeById(id);
        return  result ? ResponseResult.success(result) : ResponseResult.error(ErrorCode.NOT_FOUND.getCode(), "用户不存在");
    }

    @PostMapping("/update")
    public ResponseResult<User> updateUser(@Valid User user){
        userService.updateById(user);
        return ResponseResult.success(user);
    }

    @GetMapping("/listByParams")
    public ResponseResult<PageResult<User>> getUsersByKeyword(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @ModelAttribute UserDTO dto
    ) {
        Page<User> userPage = userService.getUsersByKeyword(page, size, dto);
        PageResult<User> pageResult = new PageResult<>(userPage.getRecords(),userPage.getTotal(),userPage.getCurrent(),userPage.getSize());
        return ResponseResult.success(pageResult);
    }

    @GetMapping("/selectGroupByAge")
    public ResponseResult<List<UserBean>> selectGroupByAge(){
        return ResponseResult.success(userService.selectGroupByAge());
    }
}
